package br.com.jorganizer.model.filter.folder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import br.com.jorganizer.model.filter.Filter;
import br.com.jorganizer.model.filterrule.FilterRule;

/**
 * Class with a Rules and a folder
 * returns files according with rules
 * @author Luciano
 *
 */

public class FolderFilter implements Filter {

	private File folder;
	private FilterRule[] rules;
	private boolean recursive;

	public FolderFilter(File folder, FilterRule[] rules, boolean recursive) {

		if (folder == null)
			throw new NullPointerException("folder");
		if (rules == null)
			throw new NullPointerException("rules");

		this.folder = folder;
		this.rules = rules;
		this.recursive = recursive;

		if (folder.exists() && !folder.isDirectory())
			throw new IllegalArgumentException(
					"Path is a file, should be a folder");
	}

	
	
	public List<File> getFiles() {
		List<File> _return = new ArrayList<File>();
		explore(folder, _return,recursive);
		return _return;

	}

	private void explore(File directory, List<File> files,boolean recursive) {
		for (File file : directory.listFiles()) {
			if (file.isDirectory() && recursive) {
				explore(file, files,recursive);
			} else {
				if (checkRules(file))
					files.add(file);
			}
		}
	}

	private boolean checkRules(File file) {
		for (FilterRule rule : rules) {
			if (rule.accepted(file.getName())) {
				return true;
			}
		}
		return false;
	}

}
